package com.ruoyi.slope.device.dataDownload.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.slope.device.dataDownload.domain.SlopeFileTask;
import com.ruoyi.slope.device.dataDownload.service.ISlopeFileTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 数据下载Controller
 * 
 * @author ruoyi
 * @date 2025-04-25
 */
@RestController
@RequestMapping("/dataDownload/dataDownload")
public class SlopeFileTaskController extends BaseController
{
    @Autowired
    private ISlopeFileTaskService slopeFileTaskService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询数据下载列表
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:list')")
    @GetMapping("/list")
    public TableDataInfo list(SlopeFileTask slopeFileTask)
    {
        startPage();
        List<SlopeFileTask> list = slopeFileTaskService.selectSlopeFileTaskList(slopeFileTask);
        return getDataTable(list);
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;

            // 从 request 获取参数，例如设备 SN、用户 ID、数据类型等
            String deviceSn = request.getParameter("deviceSn");
            String dataType = request.getParameter("dataType");
            String username = SecurityUtils.getUsername();

            // 创建 SlopeFileTask 实例
            SlopeFileTask slopeFileTask = new SlopeFileTask();
            slopeFileTask.setFileName(fileName);
            slopeFileTask.setDeviceSn(deviceSn);
            slopeFileTask.setUserId(username);
            slopeFileTask.setDataType(dataType);
            slopeFileTask.setGenerateTime(new Date());
            slopeFileTask.setGenerateStatus(0L); // 默认状态
            slopeFileTask.setDelFlag(0L); // 默认存在

            // 保存到数据库（假设你有 SlopeFileTaskService）
            slopeFileTaskService.insertSlopeFileTask(slopeFileTask);

            // 返回上传结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 导出数据下载列表
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:export')")
    @Log(title = "数据下载", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SlopeFileTask slopeFileTask)
    {
        List<SlopeFileTask> list = slopeFileTaskService.selectSlopeFileTaskList(slopeFileTask);
        ExcelUtil<SlopeFileTask> util = new ExcelUtil<SlopeFileTask>(SlopeFileTask.class);
        String path = util.exportExcel(response, list, "数据下载数据");
    }

    /**
     * 获取数据下载详细信息
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(slopeFileTaskService.selectSlopeFileTaskById(id));
    }

    /**
     * 新增数据下载
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:add')")
    @Log(title = "数据下载", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SlopeFileTask slopeFileTask)
    {
        return toAjax(slopeFileTaskService.insertSlopeFileTask(slopeFileTask));
    }

    /**
     * 修改数据下载
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:edit')")
    @Log(title = "数据下载", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SlopeFileTask slopeFileTask)
    {
        return toAjax(slopeFileTaskService.updateSlopeFileTask(slopeFileTask));
    }

    /**
     * 删除数据下载
     */
    @PreAuthorize("@ss.hasPermi('dataDownload:dataDownload:remove')")
    @Log(title = "数据下载", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(slopeFileTaskService.deleteSlopeFileTaskByIds(ids));
    }
}
